package com.atguigu.gulimail.product.web;

import com.atguigu.gulimail.product.entity.CategoryEntity;
import com.atguigu.gulimail.product.service.CategoryService;
import com.atguigu.gulimail.product.vo.Catalog2Vo;

import org.redisson.api.RLock;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Controller
public class IndexController {
    @Autowired
    CategoryService categoryService;
    @Autowired
    RedissonClient redisson;
    @GetMapping({"/","/index.html"})
    public String indexPage(Model model){
       List<CategoryEntity> categoryEntities =  categoryService.getLevel1Categorys();
       model.addAttribute("categorys",categoryEntities);
       //todo 1.查出所有一级分类
        return "index";
    }
    @ResponseBody
    @GetMapping("/index/catalog.json")
    public Map<String, List<Catalog2Vo>> getCatalogJson(){
        Map<String, List<Catalog2Vo>> map = categoryService.getCatalogJson();
        RLock my = redisson.getLock("my");
        my.lock();

        try {

            Thread.sleep(3000);
        }catch (Exception e){}finally {
            System.out.println("上锁");
            my.unlock();
        }

        return map;
    }
    @ResponseBody
    @GetMapping("/hello")
    public String hello(){
        RLock my = redisson.getLock("my");
        my.lock();

        try {

            Thread.sleep(3000);
        }catch (Exception e){}finally {
            System.out.println("上锁");
            my.unlock();
        }

        return "hello";
    }
    //分布式信号量
    @ResponseBody
    @GetMapping("/part")
    public void part() throws InterruptedException {
        RSemaphore part = redisson.getSemaphore("part");
        part.acquire();
        System.out.println("停车成功");
    }
    @ResponseBody
    @GetMapping("/go")
    public void go() throws InterruptedException {
        RSemaphore part = redisson.getSemaphore("part");
        part.release();
        System.out.println("出库成功");
    }
}
